package com.mrjy.common.config.listener;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.mrjy.common.config.WebSocket;
import com.mrjy.common.entity.AccessLog;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.util.CookieUtils;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.common.util.SpringContextHelper;
import com.mrjy.maintain.bo.AccessLogBo;
import com.mrjy.maintain.bo.IAccessLogBo;
import com.mrjy.maintain.util.RoleInfoEnum;

public class SessionUserListener implements HttpSessionListener {
	
	IAccessLogBo accessLogBo = null;
	
	@Override
	public void sessionCreated(HttpSessionEvent hse) {
		
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent hse) {
//		ServletContext sc = hse.getSession().getServletContext();
//		this.ctx = WebApplicationContextUtils.getWebApplicationContext(sc);
//		accessLogBo = (IAccessLogBo) ctx.getBean("accessLogBo");
		accessLogBo = (IAccessLogBo) SpringContextHelper.getBean("accessLogBo");
		//监听session销毁
		//session销毁说明session超时, 1.退出登录   2.登录超时
		UserInfo userInfo = (UserInfo) hse.getSession().getAttribute(GlobalConstant.USER_INFO);
		//后台登录才会有jsessionId
		String sessionId = (String) hse.getSession().getAttribute("jsessionId");
		if (userInfo!=null) {
			WebSocket.removeUserSessionWebSocketMap(userInfo.getLoginCode(),hse.getSession().getId());
			WebSocket.removeSimSessionWebSocketMap(hse.getSession().getId());
			WebSocket.removeOnlineUserGroup(hse.getSession().getId());
			//普通用户访问信息不记录
			if (userInfo.getRoleId().intValue() != RoleInfoEnum.TEACHER.getRoleId() && 
					userInfo.getRoleId().intValue() != RoleInfoEnum.PARENT.getRoleId() && 
					userInfo.getRoleId().intValue() != RoleInfoEnum.STUDENT.getRoleId() && 
					StringUtils.isNotBlank(sessionId)) {
				AccessLog accessLog = new AccessLog();
				accessLog.setType("2");
				accessLogBo.txInsert(accessLog, userInfo);
			}
		}
	}
}
